package com.doujiang.tools;

import com.doujiang.domain.dto.UserMovieDataDTO;
import com.doujiang.domain.Movie;
import com.doujiang.domain.Rating;
import com.doujiang.domain.Favorite;
import com.doujiang.domain.Comment;
import com.doujiang.domain.Tag;
import com.doujiang.service.ICommentService;
import com.doujiang.service.IFavoriteService;
import com.doujiang.service.IMovieService;
import com.doujiang.service.IRatingService;
import com.doujiang.service.IUserService;
import com.doujiang.service.IMovieTagService;
import com.doujiang.service.ITagService;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class tools {

    // 静态变量存储当前memoryId
    private static String currentMemoryId = null;
    
    // 设置memoryId的静态方法
    public static void setCurrentMemoryId(String memoryId) {
        currentMemoryId = memoryId;
        System.out.println("设置当前memoryId: " + memoryId);
    }

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IRatingService ratingService;

    @Autowired
    private IFavoriteService favoriteService;

    @Autowired
    private IMovieService movieService;

    @Autowired
    private IUserService userService;
    
    @Autowired
    private IMovieTagService movieTagService;
    
    @Autowired
    private ITagService tagService;

    /**
     * 获取用户的电影数据（评论、评分、收藏等）
     * 这是AI进行深度分析的基础数据
     */
    @Tool(name = "getUserMovieData")
    public UserMovieDataDTO getUserMovieData(String userId) {
        System.out.println("=== getUserMovieData 被调用 ===");
        System.out.println("传入的userId: " + userId);
        System.out.println("静态变量currentMemoryId: " + currentMemoryId);
        
        // 使用静态变量中的memoryId
        String actualUserId = currentMemoryId;
        System.out.println("使用实际用户ID: " + actualUserId);
        
        // 如果memoryId为null或不是数字格式，无法确定用户ID
        if (actualUserId == null || !actualUserId.matches("\\d+")) {
            System.out.println("⚠️ memoryId为null或不是数字格式: " + actualUserId + "，无法确定用户ID");
            System.out.println("返回空数据");
            
            return createEmptyUserData();
        }
        
        // 将字符串转换为Long
        Long userIdLong;
        try {
            userIdLong = Long.parseLong(actualUserId);
            System.out.println("转换后的userIdLong: " + userIdLong);
        } catch (NumberFormatException e) {
            System.out.println("用户ID转换失败: " + actualUserId);
            return createEmptyUserData();
        }
        
        UserMovieDataDTO userData = new UserMovieDataDTO();
        userData.setUserId(userIdLong);
        
        // 获取用户信息
        System.out.println("正在查询用户ID: " + userIdLong);
        var user = userService.getById(userIdLong);
        if (user != null) {
            System.out.println("找到用户: " + user.getUsername());
            userData.setUsername(user.getUsername());
        } else {
            System.out.println("未找到用户ID: " + userIdLong);
            // 显示所有可用的用户ID
            System.out.println("可用的用户ID:");
            var allUsers = userService.list();
            allUsers.forEach(u -> System.out.println("  - 用户ID: " + u.getId() + ", 用户名: " + u.getUsername() + ", 邮箱: " + u.getEmail()));
        }
        
        // 获取用户评论
        System.out.println("正在查询用户评论，用户ID: " + userIdLong);
        var comments = commentService.getCommentsByUserId(userIdLong);
        System.out.println("找到评论数量: " + comments.size());
        var commentDTOs = comments.stream().map(comment -> {
            var movie = movieService.getById(comment.getMovieId());
            var dto = new UserMovieDataDTO.UserCommentDTO();
            dto.setId(comment.getId());
            dto.setContent(comment.getContent());
            dto.setMovieTitle(movie != null ? movie.getTitle() : "未知电影");
            dto.setUseful(comment.getUseful());
            dto.setCreatedAt(comment.getCreatedAt().toString());
            return dto;
        }).collect(Collectors.toList());
        userData.setComments(commentDTOs);
        
        // 获取用户评分
        var ratings = ratingService.getRatingsByUserId(userIdLong);
        var ratingDTOs = ratings.stream().map(rating -> {
            var movie = movieService.getById(rating.getMovieId());
            var dto = new UserMovieDataDTO.UserRatingDTO();
            dto.setId(rating.getId());
            dto.setScore(rating.getScore().doubleValue());
            dto.setMovieTitle(movie != null ? movie.getTitle() : "未知电影");
            dto.setCreatedAt(rating.getCreatedAt().toString());
            return dto;
        }).collect(Collectors.toList());
        userData.setRatings(ratingDTOs);
        
        // 获取用户收藏
        var favorites = favoriteService.getFavoritesByUserId(userIdLong);
        var favoriteDTOs = favorites.stream().map(favorite -> {
            var movie = movieService.getById(favorite.getMovieId());
            var dto = new UserMovieDataDTO.UserFavoriteDTO();
            dto.setId(favorite.getId());
            dto.setMovieTitle(movie != null ? movie.getTitle() : "未知电影");
            dto.setType(favorite.getType());
            dto.setCreatedAt(favorite.getCreatedAt().toString());
            return dto;
        }).collect(Collectors.toList());
        userData.setFavorites(favoriteDTOs);
        
        // 计算基础统计数据
        var stats = calculateBasicStats(userIdLong, commentDTOs, ratingDTOs, favoriteDTOs);
        userData.setStats(stats);
        
        // 添加调试信息
        printUserDataDebugInfo(userData);
        
        return userData;
    }

    /**
     * 计算基础统计数据
     * 这些是AI进行深度分析的基础数据
     */
    private UserMovieDataDTO.MovieStatsDTO calculateBasicStats(Long userId, 
            List<UserMovieDataDTO.UserCommentDTO> comments,
            List<UserMovieDataDTO.UserRatingDTO> ratings,
            List<UserMovieDataDTO.UserFavoriteDTO> favorites) {
        
        var stats = new UserMovieDataDTO.MovieStatsDTO();
        stats.setTotalComments(comments.size());
        stats.setTotalRatings(ratings.size());
        stats.setTotalFavorites(favorites.size());
        
        if (!ratings.isEmpty()) {
            double avgRating = ratings.stream()
                .mapToDouble(UserMovieDataDTO.UserRatingDTO::getScore)
                .average()
                .orElse(0.0);
            stats.setAvgRating(avgRating);
        } else {
            stats.setAvgRating(0.0);
        }
        
        // 分析用户最喜欢的电影类型
        String favoriteGenre = analyzeFavoriteGenre(userId);
        stats.setFavoriteGenre(favoriteGenre);
        
        // 分析用户最常观看的年代
        String mostWatchedYear = analyzeMostWatchedYear(userId);
        stats.setMostWatchedYear(mostWatchedYear);
        
        return stats;
    }

    /**
     * 分析用户最喜欢的电影类型
     */
    private String analyzeFavoriteGenre(Long userId) {
        try {
            // 获取用户高分电影的类型
            var userRatings = ratingService.getRatingsByUserId(userId);
            Map<String, Integer> genreCount = new HashMap<>();
            Map<String, Double> genreScoreSum = new HashMap<>();
            
            for (Rating rating : userRatings) {
                if (rating.getScore().doubleValue() >= 7.0) { // 只统计7分以上的电影
                    Movie movie = movieService.getById(rating.getMovieId());
                    if (movie != null && movie.getGenre() != null) {
                        String[] genres = movie.getGenre().split(",");
                        for (String genre : genres) {
                            genre = genre.trim();
                            genreCount.put(genre, genreCount.getOrDefault(genre, 0) + 1);
                            genreScoreSum.put(genre, genreScoreSum.getOrDefault(genre, 0.0) + rating.getScore().doubleValue());
                        }
                    }
                }
            }
            
            // 找到最喜欢的类型（综合评分次数和平均分）
            return genreCount.entrySet().stream()
                .filter(entry -> entry.getValue() >= 2) // 至少有2部电影
                .max((e1, e2) -> {
                    double score1 = (genreScoreSum.get(e1.getKey()) / e1.getValue()) * e1.getValue();
                    double score2 = (genreScoreSum.get(e2.getKey()) / e2.getValue()) * e2.getValue();
                    return Double.compare(score1, score2);
                })
                .map(Map.Entry::getKey)
                .orElse("剧情");
        } catch (Exception e) {
            return "剧情";
        }
    }

    /**
     * 分析用户最常观看的年代
     */
    private String analyzeMostWatchedYear(Long userId) {
        try {
            var userRatings = ratingService.getRatingsByUserId(userId);
            Map<String, Integer> yearCount = new HashMap<>();
            
            for (Rating rating : userRatings) {
                Movie movie = movieService.getById(rating.getMovieId());
                if (movie != null && movie.getReleaseDate() != null) {
                    String year = String.valueOf(movie.getReleaseDate().getYear() + 1900);
                    String decade = getDecade(year);
                    yearCount.put(decade, yearCount.getOrDefault(decade, 0) + 1);
                }
            }
            
            return yearCount.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("2000年代");
        } catch (Exception e) {
            return "2000年代";
        }
    }

    /**
     * 获取年代
     */
    private String getDecade(String year) {
        int yearInt = Integer.parseInt(year);
        if (yearInt >= 2020) return "2020年代";
        else if (yearInt >= 2010) return "2010年代";
        else if (yearInt >= 2000) return "2000年代";
        else if (yearInt >= 1990) return "1990年代";
        else if (yearInt >= 1980) return "1980年代";
        else return "经典年代";
    }

    /**
     * 创建空的用户数据
     */
    private UserMovieDataDTO createEmptyUserData() {
        UserMovieDataDTO emptyData = new UserMovieDataDTO();
        emptyData.setUserId(0L);
        emptyData.setUsername("未知用户");
        emptyData.setComments(List.of());
        emptyData.setRatings(List.of());
        emptyData.setFavorites(List.of());
        
        var emptyStats = new UserMovieDataDTO.MovieStatsDTO();
        emptyStats.setTotalComments(0);
        emptyStats.setTotalRatings(0);
        emptyStats.setTotalFavorites(0);
        emptyStats.setAvgRating(0.0);
        emptyStats.setFavoriteGenre("剧情");
        emptyStats.setMostWatchedYear("2000年代");
        emptyData.setStats(emptyStats);
        
        return emptyData;
    }

    /**
     * 打印用户数据调试信息
     */
    private void printUserDataDebugInfo(UserMovieDataDTO userData) {
        System.out.println("=== 工具返回的数据 ===");
        System.out.println("用户ID: " + userData.getUserId());
        System.out.println("用户名: " + userData.getUsername());
        System.out.println("评论数量: " + userData.getComments().size());
        System.out.println("评分数量: " + userData.getRatings().size());
        System.out.println("收藏数量: " + userData.getFavorites().size());
        System.out.println("总评论数: " + userData.getStats().getTotalComments());
        System.out.println("总评分数: " + userData.getStats().getTotalRatings());
        System.out.println("总收藏数: " + userData.getStats().getTotalFavorites());
        System.out.println("平均评分: " + userData.getStats().getAvgRating());
        System.out.println("最喜欢的类型: " + userData.getStats().getFavoriteGenre());
        System.out.println("最常观看年代: " + userData.getStats().getMostWatchedYear());
        
        if (!userData.getComments().isEmpty()) {
            System.out.println("评论示例: " + userData.getComments().get(0).getContent());
        }
        if (!userData.getRatings().isEmpty()) {
            System.out.println("评分示例: " + userData.getRatings().get(0).getScore() + " - " + userData.getRatings().get(0).getMovieTitle());
        }
    }

    /**
     * 获取电影详细信息
     * 供AI在推荐时获取电影的具体信息
     */
    @Tool(name = "getMovieDetails")
    public String getMovieDetails(String movieId) {
        try {
            Long movieIdLong = Long.parseLong(movieId);
            Movie movie = movieService.getById(movieIdLong);
            
            if (movie == null) {
                return "未找到ID为 " + movieId + " 的电影";
            }
            
            StringBuilder details = new StringBuilder();
            details.append("🎬 电影详情：《").append(movie.getTitle()).append("》\n\n");
            
            // 基本信息
            details.append("📋 基本信息：\n");
            details.append("- 导演：").append(movie.getDirector() != null ? movie.getDirector() : "未知").append("\n");
            details.append("- 主演：").append(movie.getActors() != null ? movie.getActors() : "未知").append("\n");
            details.append("- 类型：").append(movie.getGenre() != null ? movie.getGenre() : "未知").append("\n");
            if (movie.getReleaseDate() != null) {
                details.append("- 上映时间：").append(movie.getReleaseDate()).append("\n");
            }
            if (movie.getDuration() != null) {
                details.append("- 时长：").append(movie.getDuration()).append("分钟\n");
            }
            details.append("\n");
            
            // 标签信息
            try {
                List<Tag> tags = movieTagService.getTagsByMovieId(movieIdLong);
                if (!tags.isEmpty()) {
                    details.append("🏷️ 标签：\n");
                    String tagNames = tags.stream()
                        .map(Tag::getName)
                        .collect(Collectors.joining("、"));
                    details.append("- ").append(tagNames).append("\n\n");
                }
            } catch (Exception e) {
                System.err.println("获取电影标签失败: " + e.getMessage());
            }
            
            // 评分统计
            double avgRating = getMovieAverageRating(movieIdLong);
            long ratingCount = ratingService.getRatingsByMovieId(movieIdLong).size();
            long commentCount = commentService.lambdaQuery()
                .eq(Comment::getMovieId, movieIdLong)
                .count();
            
            details.append("📊 用户评价：\n");
            details.append("- 平均评分：").append(String.format("%.1f", avgRating)).append("分\n");
            details.append("- 评分人数：").append(ratingCount).append("人\n");
            details.append("- 评论数量：").append(commentCount).append("条\n\n");
            
            // 简介
            if (movie.getDescription() != null && !movie.getDescription().trim().isEmpty()) {
                details.append("📖 剧情简介：\n");
                details.append(movie.getDescription()).append("\n\n");
            }
            
            return details.toString();
        } catch (NumberFormatException e) {
            return "电影ID格式错误：" + movieId;
        } catch (Exception e) {
            return "获取电影详情失败：" + e.getMessage();
        }
    }

    /**
     * 获取电影平均评分
     */
    private double getMovieAverageRating(Long movieId) {
        try {
            return ratingService.selectRatingByMovieId(movieId).doubleValue();
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 获取所有电影列表
     * 供AI在推荐时选择电影
     */
    @Tool(name = "getAllMovies")
    public String getAllMovies() {
        try {
            List<Movie> movies = movieService.list();
            StringBuilder result = new StringBuilder();
            result.append("📚 数据库中的所有电影（共").append(movies.size()).append("部）：\n\n");
            
            // 按类型分组显示
            Map<String, List<Movie>> moviesByGenre = movies.stream()
                .collect(Collectors.groupingBy(movie -> {
                    if (movie.getGenre() != null && !movie.getGenre().isEmpty()) {
                        return movie.getGenre().split(",")[0].trim(); // 取第一个类型
                    }
                    return "其他";
                }));
            
            moviesByGenre.forEach((genre, movieList) -> {
                result.append("🎭 ").append(genre).append("（").append(movieList.size()).append("部）：\n");
                movieList.stream()
                    .limit(10) // 每个类型最多显示10部
                    .forEach(movie -> {
                        double avgRating = getMovieAverageRating(movie.getId());
                        result.append("  - 《").append(movie.getTitle()).append("》");
                        if (avgRating > 0) {
                            result.append(" (评分").append(String.format("%.1f", avgRating)).append(")");
                        }
                        result.append("\n");
                    });
                if (movieList.size() > 10) {
                    result.append("  ... 还有").append(movieList.size() - 10).append("部\n");
                }
                result.append("\n");
            });
            
            return result.toString();
        } catch (Exception e) {
            return "获取电影列表失败：" + e.getMessage();
        }
    }

    /**
     * 根据类型获取电影
     * 供AI在推荐时按类型筛选电影
     */
    @Tool(name = "getMoviesByGenre")
    public String getMoviesByGenre(String genre) {
        try {
            List<Movie> allMovies = movieService.list();
            List<Movie> filteredMovies = allMovies.stream()
                .filter(movie -> movie.getGenre() != null && movie.getGenre().contains(genre))
                .collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder();
            result.append("🎭 ").append(genre).append("类型电影（共").append(filteredMovies.size()).append("部）：\n\n");
            
            filteredMovies.stream()
                .limit(20) // 最多显示20部
                .forEach(movie -> {
                    double avgRating = getMovieAverageRating(movie.getId());
                    result.append("🎬 《").append(movie.getTitle()).append("》");
                    if (movie.getDirector() != null) {
                        result.append(" - 导演：").append(movie.getDirector());
                    }
                    if (avgRating > 0) {
                        result.append(" (评分").append(String.format("%.1f", avgRating)).append(")");
                    }
                    result.append("\n");
                });
            
            if (filteredMovies.size() > 20) {
                result.append("\n... 还有").append(filteredMovies.size() - 20).append("部电影");
            }
            
            return result.toString();
        } catch (Exception e) {
            return "获取" + genre + "类型电影失败：" + e.getMessage();
        }
    }

    /**
     * 获取高分电影列表
     * 供AI在推荐时选择高分电影
     */
    @Tool(name = "getHighRatedMovies")
    public String getHighRatedMovies(String minRating) {
        try {
            double minRatingDouble = Double.parseDouble(minRating);
            List<Movie> allMovies = movieService.list();
            
            List<Movie> highRatedMovies = allMovies.stream()
                .filter(movie -> {
                    double avgRating = getMovieAverageRating(movie.getId());
                    return avgRating >= minRatingDouble;
                })
                .sorted((m1, m2) -> Double.compare(getMovieAverageRating(m2.getId()), getMovieAverageRating(m1.getId())))
                .collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder();
            result.append("⭐ 评分≥").append(minRating).append("分的高分电影（共").append(highRatedMovies.size()).append("部）：\n\n");
            
            highRatedMovies.stream()
                .limit(15) // 最多显示15部
                .forEach(movie -> {
                    double avgRating = getMovieAverageRating(movie.getId());
                    result.append("🎬 《").append(movie.getTitle()).append("》");
                    result.append(" - 评分：").append(String.format("%.1f", avgRating)).append("分");
                    if (movie.getGenre() != null) {
                        result.append(" - 类型：").append(movie.getGenre());
                    }
                    result.append("\n");
                });
            
            if (highRatedMovies.size() > 15) {
                result.append("\n... 还有").append(highRatedMovies.size() - 15).append("部高分电影");
            }
            
            return result.toString();
        } catch (NumberFormatException e) {
            return "评分格式错误，请输入数字（如：8.0）";
        } catch (Exception e) {
            return "获取高分电影失败：" + e.getMessage();
        }
    }

    /**
     * 获取热门电影列表
     * 基于评分人数和评论数确定热门程度
     */
    @Tool(name = "getPopularMovies")
    public String getPopularMovies() {
        try {
            List<Movie> allMovies = movieService.list();
            
            // 计算每部电影的受欢迎程度分数
            List<MovieWithPopularity> moviesWithPopularity = allMovies.stream()
                .map(movie -> {
                    double popularityScore = calculatePopularityScore(movie.getId());
                    return new MovieWithPopularity(movie, popularityScore);
                })
                .filter(m -> m.popularityScore > 0)
                .sorted((m1, m2) -> Double.compare(m2.popularityScore, m1.popularityScore))
                .collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder();
            result.append("🔥 热门电影排行榜（基于评分人数和评论数）：\n\n");
            
            moviesWithPopularity.stream()
                .limit(15) // 最多显示15部
                .forEach(movieWithPop -> {
                    Movie movie = movieWithPop.movie;
                    double avgRating = getMovieAverageRating(movie.getId());
                    long ratingCount = ratingService.getRatingsByMovieId(movie.getId()).size();
                    long commentCount = commentService.lambdaQuery()
                        .eq(Comment::getMovieId, movie.getId())
                        .count();
                    
                    result.append("🎬 《").append(movie.getTitle()).append("》");
                    result.append(" - 评分：").append(String.format("%.1f", avgRating)).append("分");
                    result.append(" (评分人数：").append(ratingCount).append("，评论数：").append(commentCount).append(")");
                    result.append("\n");
                });
            
            return result.toString();
        } catch (Exception e) {
            return "获取热门电影失败：" + e.getMessage();
        }
    }

    /**
     * 计算电影的受欢迎程度分数
     */
    private double calculatePopularityScore(Long movieId) {
        try {
            double avgRating = getMovieAverageRating(movieId);
            long ratingCount = ratingService.getRatingsByMovieId(movieId).size();
            long commentCount = commentService.lambdaQuery()
                .eq(Comment::getMovieId, movieId)
                .count();
            
            // 综合评分、评分人数和评论数计算受欢迎程度
            return avgRating * Math.log(ratingCount + 1) * Math.log(commentCount + 1);
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 电影与受欢迎程度的包装类
     */
    private static class MovieWithPopularity {
        final Movie movie;
        final double popularityScore;
        
        MovieWithPopularity(Movie movie, double popularityScore) {
            this.movie = movie;
            this.popularityScore = popularityScore;
        }
    }

    /**
     * 获取用户未看过的电影
     * 供AI在推荐时避免推荐用户已看过的电影
     */
    @Tool(name = "getUnwatchedMovies")
    public String getUnwatchedMovies() {
        try {
            if (currentMemoryId == null || !currentMemoryId.matches("\\d+")) {
                return "无法确定用户ID，请先登录";
            }
            
            Long userId = Long.parseLong(currentMemoryId);
            Set<Long> watchedMovieIds = getWatchedMovieIds(userId);
            
            List<Movie> allMovies = movieService.list();
            List<Movie> unwatchedMovies = allMovies.stream()
                .filter(movie -> !watchedMovieIds.contains(movie.getId()))
                .collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder();
            result.append("👀 你还没看过的电影（共").append(unwatchedMovies.size()).append("部）：\n\n");
            
            // 按类型分组显示
            Map<String, List<Movie>> moviesByGenre = unwatchedMovies.stream()
                .collect(Collectors.groupingBy(movie -> {
                    if (movie.getGenre() != null && !movie.getGenre().isEmpty()) {
                        return movie.getGenre().split(",")[0].trim();
                    }
                    return "其他";
                }));
            
            moviesByGenre.forEach((genre, movieList) -> {
                result.append("🎭 ").append(genre).append("（").append(movieList.size()).append("部）：\n");
                movieList.stream()
                    .limit(8) // 每个类型最多显示8部
                    .forEach(movie -> {
                        double avgRating = getMovieAverageRating(movie.getId());
                        result.append("  - 《").append(movie.getTitle()).append("》");
                        if (avgRating > 0) {
                            result.append(" (评分").append(String.format("%.1f", avgRating)).append(")");
                        }
                        result.append("\n");
                    });
                if (movieList.size() > 8) {
                    result.append("  ... 还有").append(movieList.size() - 8).append("部\n");
                }
                result.append("\n");
            });
            
            return result.toString();
        } catch (Exception e) {
            return "获取未看电影失败：" + e.getMessage();
        }
    }

    /**
     * 获取用户已观看的电影ID
     */
    private Set<Long> getWatchedMovieIds(Long userId) {
        Set<Long> watchedIds = new HashSet<>();
        
        // 从评分记录获取
        try {
            List<Rating> userRatings = ratingService.getRatingsByUserId(userId);
            watchedIds.addAll(userRatings.stream().map(Rating::getMovieId).collect(Collectors.toSet()));
        } catch (Exception e) {
            System.err.println("获取用户评分记录失败: " + e.getMessage());
        }
        
        // 从收藏记录获取
        try {
            List<Favorite> userFavorites = favoriteService.getFavoritesByUserId(userId);
            watchedIds.addAll(userFavorites.stream().map(Favorite::getMovieId).collect(Collectors.toSet()));
        } catch (Exception e) {
            System.err.println("获取用户收藏记录失败: " + e.getMessage());
        }
        
        return watchedIds;
    }
}
